<?php

class IndexController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        $this->registry = Zend_Registry::getInstance();
        $this->view = $this->registry['view'];
        $this->view->baseUrl = $this->_request->getBaseUrl();
    }

    public function indexAction()
    {  	
        // action body
        $this->view->title = 'ntblog的世界';
        $posts = new Posts();
        $this->view->posts = $posts->fetchAll()->toArray();
        $this->view->bodyTitle = '文章列表';
        echo $this->view->render('index/index.phtml');      
    }

    public function helloAction()
    {
    	$this->view->bodyTitle = 'Hello World!';
    	echo $this->view->render('index/hello.phtml');
    }
    
    public function editAction()
    {
    	$posts = new Posts();
    	Zend_loader::loadClass('Zend_Filter_StripTags');
    	$filter = new Zend_Filter_StripTags();
    	
    	$id = $filter->filter($this->_request->getParam('id'));
    	$this->view->posts = $posts->fetchAll('id='.$id)->toArray();
    	echo $this->view->render('index/edit.phtml');
    }
    
    public function updateAction()
    {
    	$posts = new Posts();
    	$db = $posts->getAdapter();
    	Zend_Loader::loadClass('Zend_Filter_StripTags');
    	$filter = new Zend_Filter_StripTags();
    	if(strtolower($_SERVER['REQUEST_METHOD']) == 'post'){
    		$id = $filter->filter($this->_request->getPost('id'));
    		$name = $filter->filter($this->_request->getPost('name'));		
    		$set = array('name'=>$name);
    		$where = $db->quoteInto('id=?', $id);
    		$posts->update($set, $where);
    		unset($set);
    		//echo "更新成功。返回请<a href='".$this->view->baseUrl."'>点击</a>";
    		echo "Operation was sucessful. Please click <a href='".$this->view->baseUrl."'>here</a> to return.";
    	}  	
    }
    
    public function delAction()
    {
    	$posts = new Posts();
    	$db = $posts->getAdapter();
    	Zend_Loader::loadClass('Zend_Filter_StripTags');
    	$filter = new Zend_Filter_StripTags();
    	$id = $filter->filter($this->_request->getQuery('id'));
    	$where = "id = $id";
    	$result = $posts->delete($where);
    	echo "Operation was sucessful! Please click <a href='".$this->view->baseUrl."'>here</a> to return.";
    }
    
    public function addAction()
    {
    	if(strtolower($_SERVER['REQUEST_METHOD']) == 'post'){
	    	$posts = new Posts();
	    	$db = $posts->getAdapter();
	    	Zend_Loader::loadClass('Zend_Filter_StripTags');
	    	$filter = new Zend_Filter_Striptags();
	    	$name = $filter->filter($this->_request->getPost('name'));	    	
	    	$data = array('name'=>$name);
	    	$posts->insert($data);
	    	unset($data);
	    	echo "Operation was sucessful! Please click <a href='".$this->view->baseUrl."'>here</a> to return.";
    	}else{
    		echo $this->view->render("index/add.phtml");
    	}
    }

}

